package com.begamer.card.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import sun.misc.BASE64Encoder;

public class TestMd5 {
	public static String digest(String message) {
		if (message == null || message.length() == 0)
			return null;
		try {
			byte[] msg = message.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.reset();
			md.update(msg);
			byte[] results = md.digest();

			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < results.length; i++) {
				hexString.append(Integer.toHexString(0xFF & results[i]));
			}

			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String encrypt(String message) {
		StringBuffer s = new StringBuffer();
		s.append("abc");

		if (message == null)
			return null;
		else
			message = message.substring(0, 1) + getRandomChar8()
					+ message.substring(1) + getRandomChar4();
		return (new BASE64Encoder()).encode(message.getBytes());
	}

	private static String getRandomChar8() {
		Random r = new Random();
		int i = 0;
		int c;
		char[] b = new char[8];
		while (i < 8) {
			if ((c = r.nextInt(122)) > 64) {
				b[i] = (char) c;
				i++;
			}
		}
		return new String(b);

	}

	private static String getRandomChar4() {
		Random r = new Random();
		int i = 0;
		int c;
		char[] b = new char[4];
		while (i < 4) {
			if ((c = r.nextInt(122)) > 64) {
				b[i] = (char) c;
				i++;
			}
		}
		return new String(b);

	}

	public static void main(String arg[]) {
		String s = "ISIP01002|U2009182298|0042|20100418120304|20100419|004200030001";
		System.out.println(digest(s));
		System.out.println(encrypt(s));
	}
}
